const express = require("express");
const app = express();
//跨域配置
const compression = require('compression')
app.use(compression())

const path = require("path");
const cors = require("cors");
app.use(cors());
//引入表单验证的包
const joi = require("joi");

const { CODE_ERROR, CODE_TOKEN_EXPIRED } = require("./config");

//使用body身上的数据进行解析
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
//重写res.json函数

//检验token是否过期
const expressJWT = require("express-jwt");
const { TOKEN_SECRET_KEY } = require("./config");
app.use(
  expressJWT({ secret: TOKEN_SECRET_KEY }).unless({
    path: ["/user/login", "/user/register", /file\/*/],
  })
);
//托管静态资源
// app.use("/file", express.static(path.join(__dirname, "upload")));
//引入路由
const { user, test, file } = require("./routes/index");
//使用路由
app.use("/user", user);
app.use("/test", test);
app.use("/file", file);
//err处理函数
app.use((err, req, res, next) => {
  console.log(err.message);
  if (err instanceof joi.ValidationError) {
    return res.json({ code: CODE_ERROR, msg: err.message });
  }
  if (err.name == "UnauthorizedError") {
    return res.json({ code: CODE_TOKEN_EXPIRED, msg: "登录认证已过期,请从新登录" });
  }
  return res.json({ code: CODE_ERROR, msg: err.message });
});
app.listen(8081, () => {
  console.log("server running at http://127.0.0.1");
});